package com.estun.backroundManagementService.modules.material.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.estun.backroundManagementService.config.factoryMes.ApiCaller;
import com.estun.backroundManagementService.config.properties.StationApiInfoProperties;
import com.estun.backroundManagementService.domain.factoryMes.request.FeedMaterialRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.FeedingPortRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesResponse;
import com.estun.backroundManagementService.config.properties.ApiInfoProperties;
import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.modules.material.dto.request.QrCodeRequest;
import com.estun.backroundManagementService.modules.material.dto.request.QrCodeMap;
import com.estun.backroundManagementService.modules.material.mapper.MaterialBatchMapper;
import com.estun.backroundManagementService.modules.material.mapper.MaterialMapper;
import com.estun.backroundManagementService.modules.material.mapper.MaterialPositionRelationMapper;
import com.estun.backroundManagementService.modules.material.model.Material;
import com.estun.backroundManagementService.modules.material.model.MaterialBatch;
import com.estun.backroundManagementService.modules.material.model.MaterialPositionRelation;
import com.estun.backroundManagementService.modules.material.service.MaterialBatchService;
import com.estun.backroundManagementService.modules.position.mapper.FeedingPortMapper;
import com.estun.backroundManagementService.modules.position.model.FeedingPort;
import com.estun.backroundManagementService.modules.position.model.Position;
import com.estun.backroundManagementService.modules.position.service.PositionService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
@AllArgsConstructor
public class MaterialBatchServiceImpl extends ServiceImpl<MaterialBatchMapper, MaterialBatch> implements MaterialBatchService {

    private final ApiCaller apiCaller;

    private final ApiInfoProperties apiInfoProperties;

    private final StationApiInfoProperties stationApiInfoProperties;

    private final PositionService positionService;

    @Autowired
    private FeedingPortMapper feedingPortMapper;

    @Autowired
    private MaterialPositionRelationMapper materialPositionRelationMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Override
    public BaseResponse addMaterialBatch(MaterialBatch materialBatch) {
        FeedMaterialRequest feedMaterialRequest = new FeedMaterialRequest();
        BeanUtils.copyProperties(materialBatch, feedMaterialRequest);
        feedMaterialRequest.setStationCode(positionService.getById(materialBatch.getStationCode()).getStationId());
        feedMaterialRequest.setRequestTime(LocalDateTime.now());
        BaseMesResponse post = apiCaller.post(apiInfoProperties.getSyncMaterial(), feedMaterialRequest, BaseMesResponse.class);
        log.info("【物料主数据同步】工厂MES返回:{}", post);
        if (post.isSuccess()) {
            log.info("【物料主数据同步】工厂mes调用成功,存入批次表");
            save(materialBatch);
            return BaseResponse.success("上料成功");
        } else {
            log.error("【物料主数据同步】工厂mes调用失败");
            return BaseResponse.error("工厂mes调用失败");
        }
    }

    @Override
    public BaseResponse autoAdd(QrCodeRequest qrCodeRequest) {
        Map<String, String> qrCodeMap = qrCodeRequest.getQrCodeMap();
        String stationId = qrCodeRequest.getStationCode();
        if (StringUtils.isBlank(stationId)) {
            return BaseResponse.error("工位未选择");
        }
        String invNumber = qrCodeRequest.getInvNumber();
        if (StringUtils.isBlank(invNumber)) {
            return BaseResponse.error("二维码缺失");
        }
        String materialCode = qrCodeMap.get("M");
        if (StringUtils.isBlank(materialCode)) {
            return BaseResponse.error("物料码解析失败");
        }
        List<Material> materialList = materialMapper.selectList(new QueryWrapper<Material>()
                .eq("material_code", materialCode));
        if(materialList.isEmpty()){
            return BaseResponse.error("物料码解析失败");
        }
//        Material material = materialMapper.selectOne(new QueryWrapper<Material>()
//                .eq("material_code", materialCode));
//        if (material == null) {
//            return BaseResponse.error("物料码解析失败");
//        }
        Position position = positionService.getById(stationId);
        String stationCode = position.getStationId();
        if (!position.getMaterialIdList().contains(materialCode)) {
            return BaseResponse.error("物料和工位不匹配");
        }

//        FeedingPort feedingPort = feedingPortMapper.selectFeedingPortByMaterialId(material.getId());
//
//        if (feedingPort == null || StringUtils.isBlank(feedingPort.getStationId())) {
//            return BaseResponse.error("物料上料口获取失败");
//        }
        FeedingPortRequest feedingPortRequest = new FeedingPortRequest();
        feedingPortRequest.setOpCode(stationCode);
//        feedingPortRequest.setMtName(material.getMaterialName());
        feedingPortRequest.setMtCode(materialCode);
        boolean b = openFeedingPort(feedingPortRequest);
        if(!b){
            log.error("打开上料口调用失败");
            return BaseResponse.error("打开上料口调用失败");
        }
//        try {
//            ResponseEntity<String> responseEntity = apiCaller.callStationApi(stationApiInfoProperties.getOpenFeedingPort().getUrl(), feedingPortRequest, HttpMethod.POST);
//            if (responseEntity.getStatusCode() == HttpStatus.OK) {
//                log.info("物料口已打开");
//            } else {
//                return BaseResponse.error("打开上料口接口调用失败");
//            }
//        } catch (Exception e) {
//            log.error("打开上料口调用失败:{}", e.getMessage());
//            return BaseResponse.error("打开上料口接口调用失败");
//        }

        FeedMaterialRequest feedMaterialRequest = new FeedMaterialRequest();
        feedMaterialRequest.setStationCode(positionService.getById(qrCodeRequest.getStationCode()).getStationId());
        feedMaterialRequest.setRequestTime(LocalDateTime.now());
        feedMaterialRequest.setInv(qrCodeMap.get("S"));
        BaseMesResponse<MaterialBatch> post = apiCaller.post(apiInfoProperties.getFeedMaterial(), feedMaterialRequest, BaseMesResponse.class);
        log.info("【扫码上料】工厂MES返回:{}", post);
        if (post.isSuccess()) {
            log.info("【扫码上料】工厂mes调用成功,存入批次表");
            return BaseResponse.success("上料成功");
        } else {
            log.error("【扫码上料】工厂mes调用失败");
            return BaseResponse.error("工厂mes调用失败");
        }
    }


    public boolean openFeedingPort(FeedingPortRequest feedingPortRequest) {
        try {
            ResponseEntity<String> responseEntity = apiCaller.callStationApi(stationApiInfoProperties.getOpenFeedingPort().getUrl(), feedingPortRequest, HttpMethod.POST);
//            return responseEntity.getStatusCode() == HttpStatus.OK;
            return true;
        } catch (Exception e) {
            log.error("打开上料口调用失败:{}", e.getMessage());
            return false;
        }

    }

    private static Map<String, String> parseString(String input) {
        Map<String, String> resultMap = new HashMap<>();
        String[] pairs = input.split(";");

        for (String pair : pairs) {
            if (!pair.isEmpty()) {
                String[] keyValue = pair.split(":");
                if (keyValue.length == 2) {
                    if (keyValue[1].endsWith("/")) {
                        keyValue[1] = keyValue[1].substring(0, keyValue[1].length() - 1);
                    }
                    resultMap.put(keyValue[0], keyValue[1]);
                }
            }
        }
        return resultMap;
    }
}
